/**
 * Created by 荆安喜 on 2017/11/10.
 */
$(function () {
    var ad = appData()
    var selectOne = 'hour'
    var jump = $.getUrlParam("id")
    var urlAll = {
        HbaseFWRZ: '?page=views/safeApp/logManage/probe1',
        SolrFWRZ: '?page=views/safeApp/logManage/probe2',
        MySQLFWRZ: '?page=views/safeApp/logManage/probe3',
        MongoDBFWRZ: '?page=views/safeApp/logManage/probe4',
        FTPCJRZ: '?page=views/safeApp/logManage/probe5'
    }

    $(function () {
        event()

        dataSource()
        //跳转事件
        $('.tabs-con').on('click', 'label', function () {
            var url = window.location.href.split('?')[0];
            var type = this.dataset.type
            var name = this.dataset.name
            var id = this.dataset.id
            var selectUrl = urlAll[type]
            var hour=$(this.parentElement.parentElement).find('span:eq(0)').text()
            if($("#sys-menu [data-url='views/safeApp/logManage/probe1']").length==0){
              return   _as.jAlert("<p>你的权限不足</p><p>请联系技术人员！</p>");
            }
            if(this.parentElement.parentElement.parentElement.id=='day30'){
                window.open(url + selectUrl + "&id=" + id+"&day="+hour+"&clusterId="+$('#selectFTP').val())
            }else {
                window.open(url + selectUrl + "&id=" + id+"&day="+$('#selectTime').val().replace(' ','')+"&hour="+hour+"&clusterId="+$('#selectFTP').val())
            }
        })
        //日期查看事件
        $('#day30').on('click', 'a', function () {
            var time = this.innerText
            $('#selectTime').val(time)
            $('#showOne').show()
            $(".nav-tabs a:eq(0)").click()
            drawHtml($('#selectFTP')[0].selectedOptions[0].value, $('#selectFTP')[0].selectedOptions[0].innerHTML)
            $('#shouTwo').hide()
        })

    })


    //注册事件
    function event() {

        //时间控件
        $('#selectTime').daterangepicker({
            maxDate: moment().subtract('days', 0).startOf('day'),
            singleDatePicker: true,
            showDropdowns: true,
            timePickerIncrement: 1,
            timePicker12Hour: false,
            startDate: moment().subtract('days', 0).startOf('day'),
            format: 'YYYY-MM-DD ',
            opens: 'right',
        }, function (start, end, label) {
            drawHtml($('#selectFTP').val(), $('#selectFTP')[0].selectedOptions[0].innerHTML)
        })


        $(".nav-tabs").on("click", "a", function () {
            $(this).parents().siblings().removeClass('active').end().addClass('active');
            $(".tabs-con").hide().eq($(this).parents().index()).show();
            selectOne = this.dataset.id
        })

        //选择事件
        $('#selectFTP').change(function (d) {
            if (selectOne == 'hour') {
                $('#shouTwo').show()
                drawHtml(this.value, this.selectedOptions[0].innerHTML)
                recent30Days(this.value, moment().subtract('days', 1).format('YYYY-MM-DD'))
            } else {
                $('#showOne').show()
                drawHtml(this.value, this.selectedOptions[0].innerHTML)
                recent30Days(this.value, moment().subtract('days', 1).format('YYYY-MM-DD'))
            }


        })
        //默认时间 //修改时间
        $('#selectTime').val(moment().subtract('days', 0).format('YYYY-MM-DD'))
    }


    //采集数据源
    function dataSource() {
        ad.selectList('KMGA_FTP_SOURCE', {}, function (data) {
            var str = ``
            var val
            var name
            data.forEach(function (d, i) {
                if (i == 0) {
                    val = d.key
                    name = d.value
                }
                str = str + ` <option value="${d.key}">${d.value}</option>`
            })
            $('#selectFTP').append(str)
            if(jump){
                $('#selectFTP').val(jump)
                drawHtml(val, name)
                recent30Days($('#selectFTP')[0].selectedOptions[0].value)
                history.pushState(null,'','index.html')
            }else {
                drawHtml(val, name)
                recent30Days($('#selectFTP')[0].selectedOptions[0].value)
            }

        })
    }

    //柱状图
    function histogram(id, option) {
        var myChart = echarts.init(document.getElementById(id));
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    }

    //页面渲染
    function drawHtml(id, name) {
        var timeDay=$('#selectTime').val().replace(' ','')
        var parm = {
            id: id,
            timeDay:timeDay,
            name: name
        }
        ad.selectList('KMGA_FTP_HOUR', parm, function (data) {
            collectData(data)
        })

        ad.selectList('KMGA_FTP_HOUR24', parm, function (data) {
            hour24(data, 'hour24', 'eventList', 'hour')
        })

        ad.selectList('KMGA_FTP_CHART24', parm, function (data) {
            drag(data, 'chart1')
            if (selectOne == 'day') {
                $('#showOne').hide()
            }
        })
    }

    //渲染采集源
    function collectData(data) {
        $('#collect').empty()
        $('#dataBase').empty()
        $('#total').empty()
        var collectStr = ``
        data.collectNums.forEach(function (d, i) {
            collectStr = collectStr + `<li><strong>${d.name}</strong> <div class="progress progress-striped"><div class="progress-bar progress-bar-warning" style="width: ${d.per}%">${d.per}%</div></div><em>${d.num}</em></li>`
        })

        $('#collect').append(collectStr)

        var dataBase = ``

        data.dataBaseNums.forEach(function (d, i) {
            dataBase = dataBase + ` <li><strong>${d.name}</strong>   <div class="progress progress-striped"><div class="progress-bar progress-bar-success" style="width: ${d.per}%">${d.per}%</div></div><em>${d.num}</em></li>`
        })


        $('#dataBase').append(dataBase)
        var totalStr = `<h4>${data.total.name}</h4>
                            <div class="progress progress-striped">
                                <div class="progress-bar progress-bar-warning active" style="width: ${data.total.inPer}%"></div>
                                <div class="progress-bar progress-bar-success progress-bar-striped active" style="width: ${data.total.outPer}%"></div>
                            </div>
                            <div class="flow-num"><strong class="fl">采集量：${data.total.inNum}</strong><strong class="fr">入库量：${data.total.outNum}</strong></div>`

        $('#total').append(totalStr)
        //滚动条
        $(".flow-item .scrollbar").mCustomScrollbar({
            autoHideScrollbar: true,
            advanced: {
                autoExpandHorizontalScroll: true
            }
        })

    }


    //堆叠图
    function drag(data, id) {
        var series = []
        //暖色系
        var inF=['#c4262a','#eb4c50','#f87b7e','#8f753e','#b7861f','#d29920','#edaa1c','#fbbd00','#a735d1','#be36f0','#d166f8','#eb8aff']

        //冷色系
        var out=['#2b2e54','#183988','#0071c0','#309efb','#30bbfb','#4dc40c','#93aa13','#b5be25',"#b8ce3e","#d2dc2a","#2ab8a6","#40cebc","#41ecd6","#83f2e4"]

        var comunt=0
        data.datas.forEach(function (d, i) {
            if(d.stack=='流入'){
                comunt++
            }
            var serie = {
                name: d.name,
                type: 'bar',
                stack: d.stack,
                barWidth: 25,
                data: d.data,
                itemStyle:{
                    normal:{
                        color:d.stack=='流入'?inF[i]:out[i-comunt]
                    }
                }
            }
            series.push(serie)
        })

        var option = {
            tooltip:{},
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            legend: {
                data: data.legend
            },
            xAxis: {
                data: data.xAxis
            },
            yAxis: {},
            series: series
        };
        histogram(id, option)
    }


    //24小时流量
    function hour24(data, toId, divId, jude) {
        $('#' + toId).empty()
        var str = ``
        if (jude == 'hour') {
            data.forEach(function (d, i) {
                str = str + `<li>
            <span>${d.statTime}</span>
            <span>${inflows(d.inNums)}</span>
            <span>${outflows(d.outNums)}</span>
         </li>`
            })
        } else {
            data.forEach(function (d, i) {
                str = str + `<li>
            <span><a href="javascript:void(0)">${d.statTime}</a></span>
            <span>${inflows(d.inNums)}</span>
            <span>${outflows(d.outNums)}</span>
         </li>`
            })
        }


        function inflows(c) {
            var inStr = ``
            c.forEach(function (d) {
                inStr = inStr + (d.name != 'SUM' ? `<label data-name="${d.name}" data-id="${d.id}" data-type="${d.type}">${d.name}</label>:${d.num}条,` : `==>${d.name}: ${d.num}条`)
            })
            return inStr
        }

        function outflows(c) {
            var outStr = ``
            c.forEach(function (d, i) {
                outStr = outStr + (d.name != 'SUM' ? `<label data-name="${d.name}" data-id="${d.id}" data-type="${d.type}">${d.name}</label>:${d.num}条,` : `==>${d.name}: ${d.num}条`)
            })
            return outStr
        }

        $('#' + toId).append(str)


        $("#" + divId).mCustomScrollbar({
            autoHideScrollbar: true,
            advanced: {
                autoExpandHorizontalScroll: true
            }
        })
    }


    //进30日流量曲线
    function recent30Days(id, time) {
        var parms = {
            id: id,
            startDay: '',
            endDay: time
        }

        ad.selectList('KMGA_FTP_CHART30', parms, function (data) {
            drag(data, 'chart2')
            if (selectOne == 'hour') {
                $('#shouTwo').hide()
            }
        })

        ad.selectList('KMGA_FTP_DAYS30', parms, function (data) {
            hour24(data, 'day30', 'day30List', 'day')
        })

    }

})